﻿namespace SimpleWebServices.Models
{
    using System;
    using System.Transactions;
    using System.Web.Mvc;
    using SimpleWebServices.Data;
    using SimpleWebServices.Web.UI.Html;

    public sealed class ModelBinder<T> : IModelBinder
        where T : IContainForm
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (null == controllerContext)
            {
                throw new ArgumentNullException("controllerContext");
            }

            T result = default(T);

            using (TransactionScope transaction = new TransactionScope())
            {
                result = Activator.CreateInstance<T>().Populated<T>();

                DataCollection form = DataCollection.FromPostData(controllerContext.HttpContext.Request.Form);
                result.Form.Update(form);
                result.Token = result.Form.Store(form);
                if (result.Form.IsValid)
                {
                    result.Complete(Record.Retrieve<FormSession>(result.Token.Value));
                    result.Form.Completed = true;
                }

                transaction.Complete();
            }

            return result;
        }
    }
}